<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2021/9/3
 * Time: 16:55
 */
namespace app\index\controller;


use app\BaseController;
use app\index\service\DyOpenService;
use app\index\service\Push;
use app\middleware\Check;
use Hedeqiang\TenIM\IM;
use JiaLeo\Payment\Applepay\IAP;
use JiaLeo\Payment\Common\PaymentException;
use think\facade\Db;
use think\facade\Log;
use think\facade\Queue;

class User extends BaseController{
    protected $middleware = [
        Check::class => ['except' 	=> ['orderDetail'] ]
    ];

    /**
     * 获取用户信息
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function info(){
        $user =Db::name('user')
            ->where('id',uid())
            ->find();
        if(empty($user)){
            return json(['code'=>401,'msg'=>"用户不存在",'data'=>[]]);
        }
        return success('用户信息',$user);
    }



    /**
     * 更新用户信息
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function editInfo(){
        validateParam('nickname,avatar');
        $param = input();
        $data = [];
        if(!empty($param['nickname'])){
            $data['nickname'] = $param['nickname'];
        }
        if(!empty($param['avatar'])){
            $data['avatar'] = $param['avatar'];
        }
        if(!empty($data)) {
            Db::name('user')
                ->where('id', uid())
                ->update($data);
        }
        return success('更新用户信息成功');
    }


    /**
     * 我的订单列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function myOrder(){
        validateParam('pageNo,pageSize','pageNo,pageSize');
        $param = input();

        $db = Db::name('pay_order')
            ->alias('a')
            ->field('a.id, a.order_no, a.status, a.pay_money, b.nickname,b.phone,c.pics, c.car_name,c.type_name')
            ->leftJoin('user b','a.user_id=b.id')
            ->leftJoin('cars c','c.id=a.car_id')
            ->where('a.user_id', uid());

        $total = $db->count();
        $offset = makeOffset($param['pageNo'],$param['pageSize']);
        $list = $db
            ->order('a.id desc')
            ->limit($offset,$param['pageSize'])
            ->select()
            ->toArray();

        foreach ($list as &$val) {
            $val['pics'] = json_decode($val['pics'], true);
        }
        return success('支付的订单列表', ['total'=>$total,'list'=>$list]);
    }


    /**
     * 订单详情
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderDetail(){
        validateParam('order_id','order_id');
        $orderId = input('order_id');

        $detail = Db::name('pay_order')
            ->alias('a')
            ->field('a.*,b.nickname,b.phone')
            ->leftJoin('user b','a.user_id=b.id')
            ->where('a.id', $orderId)
            ->find();
        $detail['driver'] = Db::name('car_driver_orders')
            ->join('car_drivers', 'car_drivers.id=car_driver_orders.car_driver_id')
            ->field(['car_driver_orders.car_no, car_drivers.*'])
            ->where(['car_driver_orders.order_id' => $detail['id'], 'car_driver_orders.is_deleted' => 0])
            ->find();
        return success('订单详情',$detail);
    }

    /**
     * 取消订单
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderCancel(){
        validateParam('order_id','order_id');
        $orderId = input('order_id');
        $order = Db::name('pay_order')->where('id', $orderId)->find();
        if (empty($order)) {
            return error('订单信息未找到');
        }

        // 判断订单状态
        if ( !in_array($order['status'], [0, 10, 11]) ) {
            return error('当前订单不允许取消');
        }
        $statu = 60;

        // 已支付订单请求退款
        if (in_array($order['status'], [10, 11])) {
            try {
                $refundTradeNo = 'r' . $order['order_no'];
                $refundOutTradeNo = (new DyOpenService())->createRefund($order['order_no'], $refundTradeNo, '用户取消订单', $order['pay_money']);
                if($refundOutTradeNo) {
                    $statu = 70;
                }
            } catch (\Exception $exception) {
                Log::info('refund error:' . $exception->getMessage());
                return error('退款失败，请稍后再试');
            }
        }

        // 更改订单状态
        Db::name('pay_order')->where('id', $orderId)->update(['status' => $statu, 'refund_out_trade_no' => $refundOutTradeNo ?? '']);
        return success('取消成功');
    }


    /**
     * 订单评价
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderComment(){
        validateParam('order_id,comment','order_id,comment');
        $orderId = input('order_id');
        $order = Db::name('pay_order')->where('id', $orderId)->find();
        if (empty($order)) {
            return error('订单信息未找到');
        }

        // 判断订单状态
        if ( !in_array($order['status'], [40]) ) {
            return error('当前订单不允许评价');
        }
        $statu = 50;

        // 更改订单状态
        Db::name('pay_order')->where('id', $orderId)->update(['status' => $statu, 'comment' => input('comment', '')]);
        return success('评价成功');
    }

    /**
     * 分享图片
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     * @throws \think\Exception
     */
    public function shareQr(){
        $type=input('type');
        if($type === 'dy') {
            $service = new DyOpenService();
            ob_end_clean();
            header('Content-type:image/png'); //输出的类型
            echo $service->createQRCode('pages/tabbar/home/index?pid=' . input('user_id'));
        }else{
            //微信
            $config = config('system.weChatDeveloper');
            $mini = \WeMini\Qrcode::instance($config);
            ob_end_clean();
            header('Content-type:image/png'); //输出的类型
            echo $mini->createMiniPath('pages/tabbar/home/index?pid=' . input('user_id'));
        }
    }

    /**
     * 开始试驾
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function startOrder(){
        validateParam('order_id','order_id');
        $orderId = input('order_id');
        $order = Db::name('pay_order')->where('id', $orderId)->find();
        if (empty($order)) {
            return error('订单信息未找到');
        }

        // 判断订单状态
        if ( !in_array($order['status'], [20]) ) {
            return error('当前订单不允许评价');
        }
        $statu = 30;

        // 更改订单状态
        Db::name('pay_order')->where('id', $orderId)->update(['status' => $statu, 'comment' => input('comment', '')]);
        return success('操作成功');
    }

    /**
     * 试驾完成
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderComplate(){
        validateParam('order_id','order_id');
        $orderId = input('order_id');
        $order = Db::name('pay_order')->where('id', $orderId)->find();
        if (empty($order)) {
            return error('订单信息未找到');
        }

        // 判断订单状态
        if ( !in_array($order['status'], [30]) ) {
            return error('当前订单状态异常');
        }
        $statu = 40;

        Db::startTrans();
        try {
            // 更改状态
            Db::name('car_driver_orders')->where(['order_id' => $orderId])->save(['status' => 1, 'comment' => input('comment', '')]);

            // 订单状态扭转为待评价
            Db::name('pay_order')->where(['id' => $orderId])->save(['status' => $statu]);;
            Db::commit();
            return success('试驾完成');
        }catch (\Exception $e){
            Db::rollback();
            return error('操作失败');
        }
    }
}